<script setup lang="ts">
import { ref, computed } from 'vue';
import type { Cart, CartItem } from "@/types/Cart"
import { useMemberStore } from '@/stores';
import { getCartItemApi, updateCartApi, deleteCartApi, moveCollectApi, selectedAllApi  } from '@/apis/cart';
import { onShow }from'@dcloudio/uni-app';
import { useGuessList } from '@/composables'

// 是否适配底部安全区域
defineProps<{
  safeAreaInsetBottom?: boolean
}>()
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const showCartList = ref(true)
const useMember = useMemberStore()
const cartData = ref<Cart>()
const getCartItem = async() => {
  const res = await getCartItemApi()
  cartData.value = res.data
  showCartList.value = res.data !== null
}

// 修改商品数量
const handleChangeCount = (item:CartItem) =>{
  const data = {
    skuId:item.skuId,
    count: item.count,
    selected:item.selected,
  }
  updateCartApi(data).then(res => {
    if(res.code === 0){
      getCartItem()
    }
  })
}

// 删除商品
const handleRemove = (skuId: number) => {
  // 弹窗二次确认
  uni.showModal({
    content: '是否删除',
    confirmColor: '#f14e4e',
    success: async (res) => {
      if (res.confirm) {
        // 后端删除单品
        await deleteCartApi([skuId])
        // 重新获取列表
        getCartItem()
      }
    },
  })
}

// 修改单商品选择状态
const updateSelected = async(item:CartItem) => {
  const data = {
    skuId:item.skuId,
    count: item.count,
    selected:!item.selected,
  }
  await updateCartApi(data)
  getCartItem()
}

// 计算全选状态
const isSelectedAll = computed(() => {
  return cartData.value?.items.length && cartData.value?.items.every((v) => v.selected)
})

// 修改全选中
const updateSelectedtAll = async() => {
  const _isSelectedAll = !isSelectedAll.value
  cartData.value?.items.forEach(el => {
    el.selected = _isSelectedAll
  })
  await selectedAllApi(_isSelectedAll)
  getCartItem()
}

// 移入收藏
const handleMoveCollect = (skuId:number, spuId:number) => {
  moveCollectApi({skuId, spuId}).then(res => {
    if(res.code === 0){
      getCartItem()
    }
  })
}

// 计算选中单品列表
const selectedCartList = computed(() => {
  return cartData.value?.items.filter((v) => v.selected)
})

// 计算选中总件数
const selectedCartListCount = computed(() => {
  return selectedCartList.value!.reduce((sum, item) => sum + item.count, 0)
})

// 结算按钮
const gotoPayment = () => {
  if (selectedCartListCount.value === 0) {
    return uni.showToast({
      icon: 'none',
      title: '请选择商品',
    })
  }
  // 跳转到结算页
  uni.navigateTo({ url: '/pagesOrder/order/order?type=1' })
}

// 猜你喜欢
const { guessRef, onScrolltolower } = useGuessList()

onShow(() => {
  if(useMember.profile){
    getCartItem()
  }
})
</script>

<template>
  <scroll-view enable-back-to-top scroll-y class="scroll-view" @scrolltolower="onScrolltolower">
    <!-- 已登录: 显示购物车 -->
    <template v-if="useMember.profile">
      <!-- 购物车列表 -->
      <view class="cart-list" v-if="cartData?.items.length">
        <!-- 滑动操作分区 -->
        <uni-swipe-action>
          <!-- 滑动操作项 -->
          <view v-for="item in cartData?.items" :key="item.skuId" class="cart-goods">
            <uni-swipe-action-item  class="cart-swipe">
            <!-- 商品信息 -->
            <view class="goods">
              <!-- 选中状态 -->
              <text class="checkbox" :class="{ checked: item.selected}" @tap="updateSelected(item)"></text>
              <navigator
                :url="`/pages/goods/goods?skuId=${item.skuId}`"
                hover-class="none"
                class="navigator"
              >
                <image
                  mode="aspectFill"
                  class="picture"
                  :src="item.skuDefaultImg"
                ></image>
                <view class="meta">
                  <view class="name ellipsis">{{ item.skuTitle }}</view>
                  <view class="attrsText ellipsis">{{ item.attribute }}</view>
                  <view :class="[item.price !== item.payPrice? 'price_two':'price_one']">{{ item.price }}</view>
                  <view class="payPrice_css" v-if="item.price !== item.payPrice">
                    <text class="price_title">预估</text><view class="price">{{ item.payPrice }}</view>
                  </view>
                </view>
              </navigator>
              <!-- 商品数量 -->
              <view class="count">
                <uni-number-box v-model="item.count" :step="1" :min="1" :max="item.stock" @change="handleChangeCount(item)"/>
              </view>
            </view>
            <!-- 右侧按钮 -->
            <template #right>
              <view class="cart-swipe-right">
                <view class="view collect-view" @tap="handleMoveCollect(item.skuId, item.spuId)">
                  移入
                  收藏
                </view>
                <view class="view delete-view" @tap="handleRemove(item.skuId)">删除</view>
              </view>
            </template>
          </uni-swipe-action-item>
          </view>
          
        </uni-swipe-action>
      </view>
      <!-- 购物车空状态 -->
      <view class="cart-blank" v-else>
        <image src="../../../static/images/no-cart.png" class="image" />
        <text class="text">购物车还是空的，快来挑选好货吧</text>
        <navigator open-type="switchTab" url="/pages/index/index" hover-class="none">
          <button class="button">去首页看看</button>
        </navigator>
      </view>
      <!-- 吸底工具栏 -->
      <view class="toolbar" v-if="showCartList" :style="{ paddingBottom: safeAreaInsetBottom ? safeAreaInsets?.bottom + 'px' : 0 }">
        <text class="all" :class="{ checked: isSelectedAll }" @tap="updateSelectedtAll">全选</text>
        <view style="display: flex;justify-content: flex-end;align-items: center;">
          <view>
            <view class="price_css">
              <text class="text_total">合计:</text>
              <text class="amount_total">{{ (cartData?.payPrice?cartData?.payPrice:0).toFixed(2) }}</text>
            </view>
            <view>
              <text class="text_preferent">优惠:</text>
              <text class="amount_preferent">{{ ((cartData?.totalPrice?cartData?.totalPrice:0) - (cartData?.payPrice?cartData?.payPrice:0)).toFixed(2) }}</text>
            </view>
          </view>
            <view class="button-grounp">
            <view class="button payment-button" :class="{ disabled: selectedCartListCount === 0}" @tap="gotoPayment"> 去结算({{ selectedCartListCount }})
          </view>
        </view>
      </view>
    </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <view class="login-blank" v-else>
      <text class="text">登录后可查看购物车中的商品</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view>
    <!-- 猜你喜欢 -->
    <view style="height: 100%;">
      <PetGuess ref="guessRef" />
    </view>
    <view style="height: 130rpx;"></view>
  </scroll-view>
  
</template>


<style lang="scss">
// 根元素
page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: rgb(244, 245, 247);
}

// 滚动容器
.scroll-view {
  flex: 1;
}

// 购物车列表
.cart-list {
  padding: 0 18rpx;
  
  .cart-goods{
    padding: 8rpx;
    background-color: #fff;
    border-radius: 13rpx;
    margin: 20rpx 0;
  }

  // 购物车商品
  .goods {
    display: flex;
    padding: 20rpx 20rpx 20rpx 80rpx;
    position: relative;

    .navigator {
      display: flex;
    }

    .checkbox {
      position: absolute;
      top: 0;
      left: 0;

      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 100%;

      &::before {
        content: "\e600";
        font-family: 'iconfont' !important;
        font-size: 40rpx;
        color: #444;
      }

      &.checked::before {
        content: "\e615";
        color: red;
      }
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      height: 72rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrsText {
      line-height: 1.8;
      padding: 0 15rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .payPrice_css{
      height: 40rpx;
      width: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }

    .price_title{
      font-size: 22rpx;
      color: #f04848;
    }

    .price {
      line-height: 1;
      font-size: 24rpx;
      color: #f04848;

      &::before {
        content: '￥';
        font-size: 20rpx;
      }
    }
    .price_one{
      line-height: 1;
      font-size: 28rpx;
      color: #f04848;

      &::before {
        content: '￥';
        font-size: 24rpx;
      }
    }

    .price_two {
      line-height: 1;
      font-size: 28rpx;
      color: black;

      &::before {
        content: '￥';
        font-size: 24rpx;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 15rpx;
      right: 12rpx;
    }
  }

  .cart-swipe {
    display: block;
  }

  .cart-swipe-right {
    display: flex;
    height: 100%;

    .view {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80rpx;
      padding: 6rpx;
      line-height: 1.5;
      color: #fff;
      font-size: 26rpx;
      border-radius: 0;
    }

    .collect-view {
      background-color: rgb(255, 141, 19);
      text-align: center;
    }

    .delete-view {
      background-color: rgb(254, 54, 57);
      border-top-right-radius: 13rpx;
      border-bottom-right-radius: 13rpx;
    }
  }
}

// 空状态
.cart-blank,
.login-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 47vh;
  .image {
    width: 400rpx;
    height: 300rpx;
  }
  .text {
    color: #444;
    font-size: 26rpx;
    margin: 20rpx 0;
  }
  .button {
    width: 220rpx !important;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 20rpx;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #fff;
    background-color: red;
  }
}

// 吸底工具栏
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: var(--window-bottom);
  z-index: 1;

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;
  justify-content: space-between;


  .all {
    font-size: 24rpx;
    color: #444;
    display: flex;
    align-items: center;
  }

  .all::before {
    font-family: 'iconfont' !important;
    content: "\e600";
    font-size: 40rpx;
    margin-right: 8rpx;
  }

  .price_css{
    margin-right: 14rpx;
  }

  
  .checked::before {
    content: "\e615";
    color: red;
  }

  .text_total {
    margin-right: 8rpx;
    color: #444;
    font-size: 24rpx;
  }

  .amount_total {
    font-size: 28rpx;
    color: rgb(254, 54, 57);

    &::before {
      content: '￥';
      font-size: 26rpx;
    }
  }

  .text_preferent {
    margin-right: 8rpx;
    color: rgb(185, 185, 185);
    font-size: 20rpx;
  }

  .amount_preferent {
    font-size: 22rpx;
    color: rgb(172, 172, 172);

    &::before {
      content: '￥';
      font-size: 19rpx;
    }
  }

  

  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 72rpx;
    font-size: 26rpx;
    color: #fff;

    .button {
      width: 240rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
    }

    .payment-button {
      background: red;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
  // 底部占位空盒子
  .toolbar-height {
    width: 100%;
    height: 400rpx;
  }

</style>